Page({
  data: {
    arr:[],
    originalArr:[],
    arr1:[],                // 擅长领域列表
    originalArr1:[],
    arr2:[],
    originalArr2:[],
    customItem: '全部',
    region: ['河南省', '郑州市', '中原区'],
    selectedOption: "",
    selectedSkills: [],
    selectedGender: '男', // 默认选中男
    selectedMethod: '全部方式', // 默认选中全部方式

    // 擅长领域
    field: [],              // 擅长领域列表
    selectedFields: [],     // 选中的擅长领域数组
    
  },

  onLoad: function() {
    this.GetLevels();
    this.GetSpecialization();
    this.GetChargetype();
  },

  bindRegionChange: function (e) {
    this.setData({
      region: e.detail.value
    });
  },

  showActionSheet: function() {
    let that = this;
    wx.showActionSheet({
      itemList: this.data.arr, // 显示name数组
      success: function(res) {
        if (!res.cancel) {
          let selectedName = that.data.arr[res.tapIndex];
          let selectedLevel = that.data.originalArr.find(item => item.name === selectedName);
          if (selectedLevel) {
            let selectedLevelId = selectedLevel.levelId;
            that.setData({
              selectedOption: selectedName // 更新选中的name
            });
            wx.setStorageSync('selectedLevelId', selectedLevelId); // 保存对应的levelId
            console.log(selectedName, selectedLevelId); // 打印被点击的name和对应的levelId
          } else {
            console.error('未找到对应的levelId');
          }
        } else {
          console.log('用户点击取消');
        }
      },
      fail: function() {
        console.log('API调用失败');
      }
    });
  },

  selectSkill: function(e) {
    let skill = e.currentTarget.dataset.skill;
    let index = this.data.selectedSkills.indexOf(skill);z
    if (index > -1) {
      this.data.selectedSkills.splice(index, 1);
    } else {
      if (this.data.selectedSkills.length < 3) {
        this.data.selectedSkills.push(skill);
      } else {
        wx.showToast({
          title: '最多选择3个',
          icon: 'none'
        });
      }
    }
    this.setData({
      selectedSkills: this.data.selectedSkills
    });
  },

  selectGender: function(e) {
    let gender = e.currentTarget.dataset.gender;
    this.setData({
      selectedGender: gender
    });
  },

  selectMethod: function(e) {
    let method = e.currentTarget.dataset.method;
    this.setData({
      selectedMethod: method
    });
  },

  reset: function() {
    this.setData({
      selectedSkills: ['全部'],
      selectedGender: '男',
      selectedMethod: '全部方式'
    });
  },
  GetLevels:function(){
    let that = this;
    wx.request({
      url: 'http://localhost:8085/level/findAllLevel',
      method:'GET',
      success(res){
        // console.log(res.data.data);
        if (res.data.data) {
          that.setData({
            arr: res.data.data.map(item => item.name),
            originalArr:res.data.data,
          });
        } else {
          wx.showToast({ title: '获取失败', icon: 'none' });
        }
      },
      fail() {
        wx.showToast({ title: '请求失败', icon: 'none' });
      }
    })
  },
  GetSpecialization: function() {
    let that = this;
    wx.request({
        url: 'http://localhost:8085/specialization',
        method: 'GET',
        success(res) {
            if (res.data.data) {
                // 添加“全部”选项
                const allOption = { specializationId: -1, specializationName: '全部', checked: false };
                that.setData({
                    field: [allOption, ...res.data.data.map(item => ({ ...item, checked: false }))]
                });
            } else {
                wx.showToast({ title: '获取失败', icon: 'none' });
            }
        },
        fail() {
            wx.showToast({ title: '请求失败', icon: 'none' });
        }
    });
},
  GetChargetype:function(){
    let that = this;
    wx.request({
      url: 'http://localhost:8085/chargetype/selectAllChargetype',
      method:'GET',
      success(res){
        // console.log(res.data.data);
        if (res.data.data) {
          that.setData({
            arr2: res.data.data.map(item => item.chargeTypeName),
            originalArr2:res.data.data,
          });
        } else {
          wx.showToast({ title: '获取失败', icon: 'none' });
        }
      },
      fail() {
        wx.showToast({ title: '请求失败', icon: 'none' });
      }
    })
  },
  confirmFilters: function() {
    // 拼接地域信息为字符串
    const area = this.data.region.join('，');

    // 获取levelId
    const selectedLevel = this.data.originalArr.find(item => item.name === this.data.selectedOption);

    // 获取chargeTypeId
    const selectedMethod = this.data.originalArr2.find(item => item.chargeTypeName === this.data.selectedMethod);

    // 构建筛选条件对象
    const filters = {
        area: area,
        levelId: selectedLevel ? selectedLevel.levelId : null,
        gender: this.data.selectedGender !== '不限' ? this.data.selectedGender : null,
        chargeTypeId: selectedMethod ? selectedMethod.chargeTypeId : null,
        tags: this.data.selectedFields.includes(-1) ? null : this.data.selectedFields
    };

    // 过滤掉为 null 的属性
    const filteredFilters = Object.fromEntries(Object.entries(filters).filter(([_, v]) => v !== null));

    // 将筛选条件转化为 URL 参数
    const filtersQuery = encodeURIComponent(JSON.stringify(filteredFilters));

    // 输出筛选条件
    console.log("筛选条件: ", filteredFilters);

    // 跳转并传递筛选条件
    wx.navigateTo({
        url: `../select_detail/select_detail?filters=${filtersQuery}`, // 传递筛选条件作为参数
    });

    // 显示提示信息
    wx.showToast({
        title: '筛选条件已确认',
        icon: 'success'
    });
},
  handleExpertiseChange(e) {
    let values = e.detail.value;
    let field = this.data.field;
    let selectedFields = [];

    // 更新field中每个对象的checked属性
    field.forEach(item => {
        item.checked = values.includes(item.specializationId.toString());
        if (item.checked) {
            selectedFields.push(item.specializationId);
        }
    });

    // 处理“全部”选项
    if (selectedFields.includes(-1)) {
        // 如果选中了“全部”，取消其他所有选项的选中状态
        field.forEach(item => {
            if (item.specializationId !== -1) {
                item.checked = false;
            }
        });
        selectedFields = [-1];
    } else {
        // 如果取消了“全部”，允许用户重新选择其他选项
        if (selectedFields.length > 3) {
            selectedFields = selectedFields.slice(0, 3);
            field.forEach(item => {
                item.checked = selectedFields.includes(item.specializationId);
            });
        }
    }

    this.setData({
        field,
        selectedFields
    });

    console.log('当前选中的擅长领域ID：', selectedFields);
},

  onReady() {},
  onShow() {},
  onHide() {},
  onUnload() {},
  onPullDownRefresh() {},
  onReachBottom() {},
  onShareAppMessage() {}
});